package com.foreveredu.erlms.web.struts.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.foreveredu.erlms.domain.Clazz;
import com.foreveredu.erlms.domain.Department;
import com.foreveredu.erlms.service.IManagementService;


public class DropChangeAJAXAction extends AbstractBaseDispatchAction {
	private IManagementService managementService = null;

	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	// 通过下拉列表中的院系ID，获得该院系的所有班级
	public ActionForward changeDropOfClazz(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String deptId = request.getParameter("deptId");
		Department dept = managementService.findDepartmentById(Integer.parseInt(deptId));
		List<Clazz> clazzList = managementService.findClazzsOfDepartment(dept);
		if (clazzList == null) {
			return null;
		}
		// 以下为返回到前台页面html数据
		StringBuffer sb = new StringBuffer();
		sb.append("document.forms[0].clazzId.length = "
				+ (clazzList.size() + 1) + ";\n");
		sb.append("document.forms[0].clazzId.options[0].value = '0';\n");
		sb.append("document.forms[0].clazzId.options[0].text = '请选择';\n");
		sb.append("document.forms[0].clazzId.selectedIndex = 0;\n");

		for (int i = 0; i < clazzList.size(); i++) {
			Clazz c = clazzList.get(i);
			sb.append("document.forms[0].clazzId.options[" + (i + 1)
					+ "].value = '" + c.getId() + "';\n");
			sb.append("document.forms[0].clazzId.options[" + (i + 1)
					+ "].text = '" + c.getClazzId() + "';\n");
		}

		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);

		response.getWriter().write(sb.toString());

		return null;
	}


	
}